package com.gitee.faster.webdav.kernel.protocol.handler;

import com.gitee.faster.webdav.exception.NotFoundException;
import com.gitee.faster.webdav.exception.WebDavException;
import com.gitee.faster.webdav.kernel.model.Error;
import com.gitee.faster.webdav.kernel.protocol.HttpExchange;
import lombok.extern.slf4j.Slf4j;
import org.smartboot.http.common.enums.HttpStatus;

/**
 * 默认的异常处理器
 *
 * @author hongda.li
 */
@Slf4j
public class ExceptionHandlerDefault implements ExceptionHandler {

    @Override
    public void onError(HttpExchange accessor, WebDavException e) {
        // 404
        if (e instanceof NotFoundException nf) {
            this.onNotFound(accessor, nf);
            return;
        }

        log.error("服务器出现异常", e);

        // 500
        accessor.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        accessor.writeXmlResult(new Error().setException(e));
    }

    private void onNotFound(HttpExchange accessor, NotFoundException nf) {
        accessor.setHttpStatus(HttpStatus.NOT_FOUND);
        accessor.writeXmlResult(new Error().setException(nf));
    }
}
